<?php

namespace addons\facrm\library\notice\engine;

use app\admin\model\Admin;
use fast\Http;
use addons\electronics\model\Area;
use think\Log;
use think\Queue;

/**
 * 钉钉通知
 * @author amplam 122795200@qq.com
 */
class Dingding extends Server
{



    /**
     * 构造方法
     * Dingding constructor.
     * @param $config
     */
    public function __construct($config = array())
    {
        $this->config = $config;
    }

    /**
     * 发送通知
     * @param $config 配置
     * @param $data  原始数据
     * @param array $replace_data 替换数据
     * @return bool
     */
    public function send($config,$data,$replace_data=array()){
        //获取手机号
        $mobiles = (new Admin())->where('mobile', '<>', '')->where('id', 'in', $data['admin_ids'])
            ->where('status', 'normal')->column('mobile');
        if(!$mobiles) {
            $this->error ="钉钉通知需要手机哈";
            return false;
        }
        foreach ($replace_data as $k=>&$v){
            $v=strip_tags($v);
        }

        $send_data = [
            'msgtype'=>'text',
            'at'=>[
                'atMobiles' => $mobiles,
            ],
            'text'=>[
                'content' =>$config['describe'] . __("通知").":"
                    . __($config['values']['content'], $replace_data),
            ]
        ];

        $header = [
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen(json_encode($send_data)),
        ];

        $result = self::curl_post_content($config['values']['webhook'], json_encode($send_data), $header);

        $result=json_decode($result,true);
        \addons\facrm\model\Notices::add($send_data,"Dingding",$result['errcode']==0?1:'0',$result['errmsg']);

        return  $result;

    }

    public static function curl_post_content($url, $data = null, $header = [])
    {
        $ch = curl_init();
        if (substr_count($url, 'https://') > 0) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            $res = false;
        }
        curl_close($ch);

        return $res;
    }

}